package com.haoma.receiver;

import cn.hutool.json.JSONUtil;
import com.haoma.constant.RabbitConstant;
import com.haoma.dto.LinkAuditDto;
import com.haoma.service.LinkApplyForService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Description: 友链消费者监听友链生产的消息
 */
@Component
public class LinkReceiver {

    // 友链申请接口
    @Autowired
    private LinkApplyForService linkApplyForService;

    /**
     * 接收生产者审核成功的信息
     *
     * @param linkAuditDtoJson      友链id
     * @param message 接收到的完整消息对象
     * @param channel 跟mq通信的方法
     */
    @RabbitListener(
            // 存储消息的队列
            bindings = @QueueBinding(value = @Queue(value = RabbitConstant.QUEUE_LINK_SUCCESS),
                    // 转发消息的交换机
                    exchange = @Exchange(value = RabbitConstant.EXCHANGE_LINK_AUDIT),
                    // 审核成功的key
                    key = {RabbitConstant.ROUTING_LINK_SUCCESS}))
    public void auditSuccess(String linkAuditDtoJson, Message message, Channel channel) throws IOException {
        LinkAuditDto linkAuditDto = JSONUtil.toBean(linkAuditDtoJson, LinkAuditDto.class);
        if (linkAuditDto != null) {
            // 审核成功
            linkApplyForService.auditSuccess(linkAuditDto);
        }
        // 手动确认该消息通过唯一标识已被消费
        // 参数1：标号用于消息确认 记载 消息重试等
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 接收生产者审核失败的信息
     */
    @RabbitListener(
            bindings = @QueueBinding(value = @Queue(value = RabbitConstant.QUEUE_LINK_FAIL),
                    exchange = @Exchange(value = RabbitConstant.EXCHANGE_LINK_AUDIT),
                    key = {RabbitConstant.ROUTING_LINK_FAIL})
    )
    public void auditFail(String linkAuditDtoJson, Message message, Channel channel) throws IOException {
        LinkAuditDto linkAuditDto = JSONUtil.toBean(linkAuditDtoJson, LinkAuditDto.class);
        if (linkAuditDto != null) {
            // 审核失败
            linkApplyForService.auditFail(linkAuditDto);
        }
        // 确认消息通过唯一标识已经被消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
